package adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.administrator.weipiao.R;

import java.util.List;

import bean.Movies;
import loadresource.LoadImgTask;

/**
 * Created by Administrator on 2016/9/10.
 */
public class MovieAdapter extends BaseAdapter {
    private List<Movies> mData;
    private LayoutInflater mInfalater;
    public MovieAdapter(Context context) {
        mInfalater = LayoutInflater.from(context);
    }
    public void setData(List<Movies> data){
        this.mData = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mData!=null?mData.size():0;
    }

    @Override
    public Object getItem(int position) {
        return mData!=null?mData.get(position):null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        //复用ViewHolder holder
        if (convertView==null){
            convertView = mInfalater.inflate(R.layout.list_movie, parent, false);
            // 减少findViewById的次数
            holder = new ViewHolder();
            holder.imgLogo = (ImageView) convertView.findViewById(R.id.img_logo);
            holder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tvHighlight = (TextView) convertView.findViewById(R.id.tv_highlight);
            holder.tvGrade = (TextView) convertView.findViewById(R.id.tv_grade);
            holder.tvActors = (TextView) convertView.findViewById(R.id.tv_actors);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        //绑定数据
//        holder.imgLogo = mData.get(position);
        Movies movies = mData.get(position);
        holder.tvName.setText(movies.getName());
        holder.tvHighlight.setText(movies.getHighlight());
        holder.tvGrade.setText(movies.getGrade());
        holder.tvActors.setText(movies.getActors());
        //显示图片
        final String logo = movies.getLogo();
        //写一个下载图片的异步任务
        new LoadImgTask(new LoadImgTask.OnGetImageResultListener() {
            @Override
            public void onGetImageResult(Bitmap result) {
                holder.imgLogo.setImageBitmap(result);
            }
        }).execute(logo);


        return convertView;
    }

    // 注意:该内部类,要作为一个static.目的为了防止内存泄露
    static class ViewHolder{
        ImageView imgLogo;
        TextView tvName,tvHighlight,tvGrade,tvActors;
    }
}
